package study.nzy.com.studydemo;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import study.nzy.com.studydemo.utils.ToastUtils;

public class MainActivity extends Activity {

    String fruitNames[]={"苹果","香蕉","樱桃","葡萄","芒果","桔子","梨","菠萝","草莓","西瓜"};
    //定义图片资源数组
    int fruitImage[]={R.drawable.apple_pic,R.drawable.banana_pic,R.drawable.cherry_pic,R.drawable.grape_pic,R.drawable.mango_pic,R.drawable.orange_pic,R.drawable.pear_pic,R.drawable.pineapple_pic,R.drawable.strawberry_pic,R.drawable.watermelon_pic};
    GridView gv_items;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gv_items = findViewById(R.id.gv_items);
        gv_items.setAdapter(new MyAdapter(this,fruitNames,fruitImage));
        gv_items.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ToastUtils.showToast(MainActivity.this,fruitNames[i]);
            }
        });
    }
}

class MyAdapter extends BaseAdapter {

    String fruitNames[];
    int fruitImage[];
    Context context;

    MyAdapter(Context context, String[] fruitNames, int[] fruitImage){
        this.context = context;
        this.fruitNames = fruitNames;
        this.fruitImage = fruitImage;
    }

    @Override
    public int getCount() {
        return fruitNames.length;
    }

    @Override
    public Object getItem(int i) {
        return fruitNames[i];
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View rootView =  View.inflate(context,R.layout.item_fruit,null);
        TextView tv_fruit_name = rootView.findViewById(R.id.tv_fruit_name);
        tv_fruit_name.setText(getItem(i).toString());
        ImageView iv_fruit = rootView.findViewById(R.id.iv_fruit);
        iv_fruit.setImageResource(fruitImage[i]);
        return rootView;
    }
}